package com.zhongxi.guoyuan.view.shopCart;

import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.shopCart.AddressAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.shopcart.AddressList;
import com.zhongxi.guoyuan.entity.shopcart.AddressListResult;
import com.zhongxi.guoyuan.entity.shopcart.AddressResult;
import com.zhongxi.guoyuan.url.Url;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EditAddressActivity extends BaseActivity implements View.OnClickListener {

    private TextView tvSubmit;
    private ImageView ivSelect;
    private boolean isSelect;
    private String type;
    private Spinner sp1, sp2, sp3;
    private List<AddressList.AddressData> list = new ArrayList<AddressList.AddressData>();
    private List<AddressList.AddressData> cityList = new ArrayList<AddressList.AddressData>();
    private List<AddressList.AddressData> preList = new ArrayList<AddressList.AddressData>();
    private AddressAdapter adapter;
    private AddressList addressResult;
    private AddressList cityResult;
    private AddressAdapter cityAdapter;
    private AddressAdapter preAdapter;
    private int addressPos = 0;
    private int cityPos = 0;
    private int prePos = 0;
    private boolean refresh;
    private Map<String, String> map = new HashMap<String, String>();
    private EditText etUserName;
    private EditText etPhone;
    private EditText etAddress;
    private AddressList result;
    private AddressResult addResult;
    private String pid;
    private String cid;
    private String pre;
    private AddressListResult.AddressListData  data;

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_edit_address);
        initTitle();
        tvTitle.setText("添加地址");
        tvSubmit = (TextView) findViewById(R.id.tvSubmit);
        ivSelect = (ImageView) findViewById(R.id.ivSelect);
        etUserName = (EditText) findViewById(R.id.etUserName);
        etPhone = (EditText) findViewById(R.id.etPhone);
        etAddress = (EditText) findViewById(R.id.etAddress);
        sp1 = (Spinner) findViewById(R.id.sp1);
        sp2 = (Spinner) findViewById(R.id.sp2);
        sp3 = (Spinner) findViewById(R.id.sp3);
    }

    @Override
    protected void initData() {
        super.initData();
        setDefaultData();
        adapter = new AddressAdapter(this, list, 1);
        sp1.setAdapter(adapter);
        cityAdapter = new AddressAdapter(this, cityList, 2);
        sp2.setAdapter(cityAdapter);
        preAdapter = new AddressAdapter(this, preList, 3);
        sp3.setAdapter(preAdapter);
        getProvince();
    }

    /**
     * 显示默认地址
     */
    private void setDefaultData() {
        data = (AddressListResult.AddressListData) getIntent().getSerializableExtra("data");
        if(null!=data&&!"".equals(data)){
            if(null!=data.getUsername()&&!"".equals(data.getUsername())){
                etUserName.setText(data.getUsername());
            }
            if(null!=data.getMphone()&&!"".equals(data.getMphone())){
                etPhone.setText(data.getMphone());
            }
            if(null!=data.getAddress()&&!"".equals(data.getAddress())){
                etAddress.setText(data.getAddress());
            }
            if(null!=data.getPid()&&!"".equals(data.getPid())){
                pid = data.getPid();
            }
            if(null!=data.getCid()&&!"".equals(data.getCid())){
                cid = data.getCid();
            }
            if(null!=data.getPreid()&&!"".equals(data.getPreid())){
                pre = data.getPreid();
            }
        }
    }

    /**
     * 获取省份列表
     */
    private void getProvince() {
        type = "province";
        getServer(Url.PROVINCE_LIST, null, "", false, null, "get");
    }

    /**
     * 获取城市列表
     */
    private void getCity() {
        type = "city";
        String str = "";
        if(!refresh&&null!=data&&!"".equals(data)){
            str = "&pid="+data.getPid();
        }else{
            str = "&pid="+addressResult.getData().get(addressPos).getP_id();
        }
        getServer(Url.CITY_LIST, null, str, false, null, "get");
    }

    /**
     * 获取区县列表
     */
    private void getPrefecture() {
        type = "prefecture";
        String str = "";
        if(!refresh&&null!=data&&!"".equals(data)){
            str = "&pid="+data.getPid()+"&cid="+data.getCid();
        }else {
            str = "&pid=" + addressResult.getData().get(addressPos).getP_id() + "&cid=" + cityResult.getData().get(cityPos).getC_id();
        }
        Log.i("base", str);
        getServer(Url.PREFECTURE_LIST, null, str, false, null, "get");
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(this);
        tvSubmit.setOnClickListener(this);
        ivSelect.setOnClickListener(this);
        //新增配送地址
        tvSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(TextUtils.isEmpty(etUserName.getText().toString().trim())){
                    showShortToast("请输入您的姓名");
                }else if(TextUtils.isEmpty(etPhone.getText().toString().trim())){
                    showShortToast("请输入您的手机号！");
                }else if(TextUtils.isEmpty(etAddress.getText().toString().trim())){
                    showShortToast("请输入您的具体地址");
                }else if(null!=data&&!"".equals(data)){
                    editAddress();
                }else{
                    addAddress();
                }
            }
        });
        sp1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                sp1.setSelection(position);
                addressPos = position;
                if(refresh)
                    getCity();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        sp2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                sp2.setSelection(position);
                cityPos = position;
                if(refresh)
                    getPrefecture();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        sp3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                prePos = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    /**
     * 编辑地址
     */
    private void editAddress() {
        type = "edit";
        map.clear();
        map.put("aid", data.getId());
        map.put("username", etUserName.getText().toString().trim());
        map.put("mphone", etPhone.getText().toString().trim());
        map.put("pid", addressResult.getData().get(addressPos).getP_id());
        map.put("province", addressResult.getData().get(addressPos).getProvince());
        map.put("cid", cityResult.getData().get(cityPos).getC_id());
        map.put("city", cityResult.getData().get(cityPos).getCity());
        map.put("preid", result.getData().get(prePos).getPre_id());
        map.put("prefecture", result.getData().get(prePos).getPrefecture());
        map.put("address", etAddress.getText().toString().trim());
        getServer(Url.EDIT_ADDRESS, map, "", false, null, "post");
    }

    /**
     * 增加地址
     */
    private void addAddress() {
        type = "addaddress";
        map.clear();
        map.put("username", etUserName.getText().toString().trim());
        map.put("mphone", etPhone.getText().toString().trim());
        map.put("pid", addressResult.getData().get(addressPos).getP_id());
        map.put("province", addressResult.getData().get(addressPos).getProvince());
        map.put("cid", cityResult.getData().get(cityPos).getC_id());
        map.put("city", cityResult.getData().get(cityPos).getCity());
        map.put("preid", result.getData().get(prePos).getPre_id());
        map.put("prefecture", result.getData().get(prePos).getPrefecture());
        map.put("address", etAddress.getText().toString().trim());
        Log.i("base", map.toString());
        getServer(Url.Add_Address, map, "", false, null, "post");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ivBack:
                finish();
                break;
            case R.id.tvSubmit:
                //提交保存
                break;
            case R.id.ivSelect:
                isSelect=!isSelect;
                if(isSelect){
                    ivSelect.setImageResource(R.mipmap.iv_select);
                }else{
                    ivSelect.setImageResource(R.mipmap.iv_noselect);
                }
                break;
        }
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try{
            if("province".equals(type)){
                addressResult = gson.fromJson(response, AddressList.class);
                if(null!=addressResult.getSafeobj()&&!"".equals(addressResult.getSafeobj())){
                    MyApplication.getInstance().setSpValue(addressResult.getSafeobj());
                }
                list.clear();
                list.addAll(addressResult.getData());
                if(null!=pid&&!"".equals(pid)){
                    setDefault(sp1, addressResult.getData(), 1);
                }
                adapter.notifyDataSetChanged();
                getCity();
            }else if("city".equals(type)){
                cityResult = gson.fromJson(response, AddressList.class);
                if(null!=cityResult.getSafeobj()&&!"".equals(cityResult.getSafeobj())){
                    MyApplication.getInstance().setSpValue(cityResult.getSafeobj());
                }
                cityList.clear();
                cityList.addAll(cityResult.getData());
                if(null!=cid&&!"".equals(cid)){
                    setDefault(sp2, cityResult.getData(), 2);
                }
                cityAdapter.notifyDataSetChanged();
                getPrefecture();
            }else if("prefecture".equals(type)){
                result = gson.fromJson(response, AddressList.class);
                if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj())){
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                preList.clear();
                preList.addAll(result.getData());
                if(null!=pre&&!"".equals(pre)){
                    setDefault(sp3, result.getData(), 3);
                }
                preAdapter.notifyDataSetChanged();
                refresh = true;
            }else if("addaddress".equals(type)){
                addResult = gson.fromJson(response, AddressResult.class);
                if(null!=addResult.getSafeobj()&&!"".equals(addResult.getSafeobj())){
                    MyApplication.getInstance().setSpValue(addResult.getSafeobj());
                }
                showShortToast("添加地址成功");
                if(isSelect){
                    setDefaultAddress();
                }else{
                    finish();
                }
            }else if("default".equals(type)){
                BaseResponse result = gson.fromJson(response, BaseResponse.class);
                if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj())){
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                showShortToast("默认地址设置成功");
                finish();
            }else if("edit".equals(type)){
                BaseResponse result = gson.fromJson(response, BaseResponse.class);
                if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj())){
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                showShortToast("编辑地址成功");
                if(isSelect){
                    setDefaultAddress();
                }else{
                    finish();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 设置默认选中省、市、区
     * @param addressDatas
     */
    private void setDefault(Spinner sp, List<AddressList.AddressData> addressDatas, int type) {
        for(int i=0;i<addressDatas.size();i++){
            if(type == 1){
                if(addressDatas.get(i).getP_id().equals(pid)){
                    sp.setSelection(i);
                }
            }else if(type == 2){
                if(addressDatas.get(i).getC_id().equals(cid)){
                    sp.setSelection(i);
                }
            }else if(type == 3) {
                if(addressDatas.get(i).getPre_id().equals(pre)){
                    sp.setSelection(i);
                }
            }
        }
    }

    /**
     * 配送地址为默认地址
     */
    private void setDefaultAddress() {
        type = "default";
        String str = "";
        if(null!=data&&!"".equals(data)){
            str = "&aid="+data.getId();
        }else{
            str = "&aid="+addResult.getId();
        }
        getServer(Url.DEFAULT_ADDRESS, null, str, false, null, "get");
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try{
            BaseResponse response1 = gson.fromJson(response, BaseResponse.class);
            if(null!=response1&&!"".equals(response1)){
                MyApplication.getInstance().setSpValue(response1.getSafeobj());
            }
            if(2201==response1.getCode()){
                showShortToast("编辑地址失败");
            }else if(2202 == response1.getCode()){
                showShortToast("收货地址超限");
            }else if(2203 == response1.getCode()){
                showShortToast("设置默认地址失败");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
